<template>
  <view>
    <view class="goods-list">
      <view v-for="(goods,i) in goodsList" :key="i" @click="gotoDetail(goods)">
        <my-goods :goods="goods"></my-goods>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        queryObj: {
          query: '',
          cid: '',
          pagenum: 1,
          pagesize: 20
        },
        // 商品列表数据
        goodsList: [],
        //商品总数，用于实现分页
        total: 0,
        //节流阀，是否正在请求数据
        isloading: false
      };
    },
    onLoad(options) {
      console.log(options);
      this.queryObj.query = options.query || ''
      this.queryObj.cid = options.cid || ''

      console.log(this.queryObj);

      //获取商品列表数据
      this.getGoodsList()
    },
    methods: {
      async getGoodsList(cb) {
        //打开节流阀
        this.isloading = true
        const {
          data: res
        } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
        //关闭节流阀
        this.isloading = false
        cb && cb()

        // console.log(res);
        if (res.meta.status !== 200) {
          return uni.$showMsg()
        }
        //展开运算符
        this.goodsList = [...this.goodsList, ...res.message.goods]
        this.total = res.message.total
      },
      gotoDetail(item) {
        uni.navigateTo({
          url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id
        })
      }
    },

    //上拉加载
    onReachBottom() {
      if (this.queryObj.pagenum > this.total / this.queryObj.pagesize) {
        return uni.$showMsg('数据已全部加载完毕！')
      }
      if (this.isloading) {
        return
      }

      //页码数+1
      this.queryObj.pagenum += 1
      //重新发送请求，获取数据
      this.getGoodsList()
    },

    //下拉刷新
    onPullDownRefresh() {
      //重置关键数据
      this.queryObj.pagenum = 1,
        this.total = 0,
        this.isloading = false
      this.goodsList = []

      //重新发起请求,请求完毕后调用回调函数，关闭下拉刷新
      this.getGoodsList(() => uni.stopPullDownRefresh())
    }
  }
</script>

<style lang="scss">
  .goods-list {
    background-color: white;
  }
</style>